package com.quanshu.exchange.ui.gui.message.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.db.GroupDao;
import com.quanshu.exchange.support.db.UserDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.GroupMemberEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.message.group.dialog.DialogHandOverGroupOwner;

import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by jye on 2018/1/21.
 */

public class HandOverGroupOwnerActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.commit_btn)
    LinearLayout commitBtn;
    @BindView(R.id.content_recycler_view)
    RecyclerView contentRecyclerView;
    private SingleAdapter adapter;
    private GroupEntity groupEntity;
    private String selectedUserId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hand_over_group_owner);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initData();
        initListener();
    }

    private void initIntent() {
        groupEntity = (GroupEntity) getIntent().getSerializableExtra("GroupEntity");
    }

    private void initView() {

        contentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter(new DataDisplayer<GroupMemberEntity>(this, R.layout.item_select_new_group_owner) {
            @Override
            public void bindData(BaseViewHolder holder, LayoutWrapper wrapper, GroupMemberEntity item, int position) {
                holder.setRoundImageUrl(R.id.group_member_avatar, item.getPhoto(), R.drawable.default_avatar);
                UserEntity userEntity = UserDao.getInstance().query(item.getMemberid());
                if (userEntity != null) {
                    holder.setText(R.id.group_member_name, AppUtils.getUserName(userEntity));
                } else {
                    holder.setText(R.id.group_member_name, item.getNickname());
                }
                ImageView imageView = holder.getView(R.id.group_member_check);
                if (selectedUserId != null && selectedUserId.equals(item.getMemberid())) {
                    imageView.setSelected(true);
                } else {
                    imageView.setSelected(false);
                }
                holder.setOnClickListener(R.id.group_member_check, view -> {
                    imageView.setSelected(true);
                    selectedUserId = item.getMemberid();
                    adapter.notifyDataSetChanged();
                });
            }
        });
        contentRecyclerView.setAdapter(adapter);
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
        RxViewHelper.getInstance().clicks(commitBtn, aVoid -> doShowDialog(selectedUserId));
    }

    private void initData() {

        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getGroupMembers(AppUtils.getSignParams(String.valueOf(groupEntity.getGroup_id())), groupEntity.getGroup_id())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<List<GroupMemberEntity>>>() {
                    @Override
                    public void onSuccess(BaseResponse<List<GroupMemberEntity>> response) {
                        List<GroupMemberEntity> info = response.getInfo();
                        Iterator<GroupMemberEntity> it = info.iterator();
                        while (it.hasNext()) {
                            GroupMemberEntity groupMemberEntity = it.next();
                            if (groupMemberEntity.getMemberid().equals(currentUser.getMemberid())) {
                                it.remove();
                            }
                        }
                        adapter.setData(info);
                    }
                });
    }

    private void doShowDialog(String memberId) {
        if (memberId == null || memberId.trim().length() < 1) {
            ToastHelper.toast("请选择移交对象");
            return;
        }
        if (memberId.equals(groupEntity.getOwner())) {
            ToastHelper.toast("此账号是当前群主，请重新选择");
            return;
        }
        DialogHandOverGroupOwner dialog = new DialogHandOverGroupOwner(this);
        dialog.show();
        dialog.setTitle(memberId);
        dialog.getOkSubject().subscribe(o -> doHandOver(memberId));
    }

    private void doHandOver(String memberId) {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .handoverGroupOwner(AppUtils.getSignParams(groupEntity.getOwner(), memberId, groupEntity.getHx_groupid()), groupEntity.getOwner(), memberId, groupEntity.getHx_groupid())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        groupEntity.setOwner(memberId);
                        GroupDao.getInstance().save(groupEntity);
                        EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                        //支持单聊和群聊，默认单聊，如果是群聊添加下面这行
                        cmdMsg.setChatType(EMMessage.ChatType.GroupChat);
                        String action = "group_change_owner";//action可以自定义
                        EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
                        cmdMsg.setTo(groupEntity.getHx_groupid());//发送给某个人
                        cmdMsg.setAttribute("new_owner", memberId);
                        cmdMsg.addBody(cmdBody);
                        EMClient.getInstance().chatManager().sendMessage(cmdMsg);

                        Intent intent = getIntent();
                        intent.putExtra("GroupEntity", groupEntity);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

}
